<template xlang="wxml">
	<view class="">
	<view class="uni-data-tree-input" @click="handleInput">
		<slot :data="inputSelected" :error="errorMessage">
			<view class="input-value"> 
				<text v-if="errorMessage" class="selected-area error-text">{{errorMessage}}</text>
				<view v-else-if="loading && !isOpened" class="selected-area">
					<uni-load-more class="load-more" :contentText="loadMore" status="loading"></uni-load-more>
				</view>
				<scroll-view v-else-if="inputSelected.length" class="selected-area" scroll-x="true">
					<view class="selected-list">
						<view class="selected-item" v-for="(item,index) in inputSelected" :key="index">
							<text>{{item.text}}</text>
							<!-- <text v-if="index<inputSelected.length-1" class="input-split-line">{{split}}</text> -->
							<!-- 管理员法人不能删除 && item.id != $store.getters.staffInfo.adminId && item.id != $store.getters.staffInfo.legalId && isAdminId -->
							<view class="icon-clear" @click.stop="clear(item,index)" v-if="clearIcon && inputSelected.length ">
								<uni-icons type="clear" color="#e1e1e1" size="14"></uni-icons>
							</view>
							<!-- 管理员法人可以删除 -->
							<!-- <view class="icon-clear" @click.stop="clear(item,index)" v-if="clearIcon && inputSelected.length && !isAdminId">
								<uni-icons type="clear" color="#e1e1e1" size="14"></uni-icons>
							</view> -->
						</view>
				</view>
				</scroll-view>
				<text v-else class="selected-area placeholder">{{placeholder}}</text>
				<!-- 旋转箭头显示 --> 
				<view class="arrow-area">
					<view class="input-arrow"></view>
				</view>
			</view>
		</slot>
	</view>
	<view class="uni-data-tree-cover" v-if="isOpened && !disabled" @click="handleClose"></view>
	<view class="tki-tree" v-if="isOpened && !disabled">
		<view class="tki-tree-mask" :class="{'show':showTree}" @tap="_cancel"></view>
		<view class="tki-tree-cnt" :class="{'show':showTree}">
			<view class="tki-tree-bar">
				<view class="tki-tree-bar-cancel" :style="{'color':cancelColor}" hover-class="hover-c" @tap="_cancel">取消</view>
				<view class="tki-tree-bar-title" :style="{'color':titleColor}">{{title}}</view>
				<view class="tki-tree-bar-confirm" :style="{'color':confirmColor}" hover-class="hover-c" @tap="_confirm">确定</view>
			</view>
			<view class="tki-tree-view">
				<scroll-view class="tki-tree-view-sc" :scroll-y="true">
					<block v-for="(item, index) in treeList" :key="index">
						<view class="tki-tree-item" :style="[{
							paddingLeft: item.rank*15 + 'px',
							zIndex: item.rank*-1 +50
						}]"
						 :class="{
							border: border === true,
							show: item.show,
							last: item.lastRank,
							showchild: item.showChild,
							open: item.open,
						}">
						<!-- ?(item.id != $store.getters.staffInfo.adminId && item.id != $store.getters.staffInfo.legalId):true -->
							<view class="tki-tree-label" @tap.stop="_treeItemTap(item, index)" v-if="isAdminId">
								<image class="tki-tree-icon" :src="item.lastRank ? lastIcon : item.showChild ? currentIcon : defaultIcon" />
								{{item.label}}<span v-if="!!item.staffPost">（{{item.staffPost}}）</span>
							</view>
							<view class="tki-tree-label" v-else>
								<image class="tki-tree-icon" :src="item.lastRank ? lastIcon : item.showChild ? currentIcon : defaultIcon" />
								{{item.label}}<span v-if="!!item.staffPost">（{{item.staffPost}}）</span>
							</view>
							<!-- 选择框 ?(item.id != $store.getters.staffInfo.adminId && item.id != $store.getters.staffInfo.legalId):true -->
							<view v-if="isAdminId">
							<view class="tki-tree-check" @tap.stop="_treeItemSelect(item, index)" v-if="selectParent?true:item.lastRank">
								<view class="tki-tree-check-yes" v-if="item.checked" :class="{'radio':!multiple}" :style="{'border-color':confirmColor}">
									<view class="tki-tree-check-yes-b" :style="{'background-color':confirmColor}"></view>
								</view>
								<view class="tki-tree-check-no" v-else :class="{'radio':!multiple}" :style="{'border-color':confirmColor}"></view>
						</view>
						</view>
						<!-- 默认选择 -->
						<view class="tki-tree-check" v-else>
							<view class="tki-tree-check-yes" v-if="item.checked" :class="{'radio':!multiple}" :style="{'border-color':confirmColor}">
								<view class="tki-tree-check-yes-b" :style="{'background-color':confirmColor}"></view>
							</view>
							<view class="tki-tree-check-no" v-else :class="{'radio':!multiple}" :style="{'border-color':confirmColor}"></view>
						</view>
						
						</view>
					</block>
				</scroll-view>
			</view>
		</view>
	</view>
	</view>
</template>

<script>
	export default {
		name: "tki-tree",
		props: {
			// 是否禁用 
			disabled:{
				type: Boolean,
				default: false
			},
			// 默认显示
			defaultRange:{
				type: Array,
				default: function() {
					return []
				}
			},
			// 是否展开所有节点 
            showAllFlod: {
				type: Boolean,
				default: false
			},
			openRank: {
				type: [Number, String],
			},
			split: {
				type: String,
				default: '/'
			},
			clearIcon: {
				type: Boolean,
				default: true
			},
			// 默认是否选择管理员 
			isAdminId: {
				type: Boolean,
				default: true
			},
			placeholder: {
				type: String,
				default: '请选择'
			},
			lazy: {
				type: Boolean,
				default: false
			},
			range: {
				type: Array,
				default: function() {
					return []
				}
			},
			idKey: {
				type: String,
				default: 'id'
			},
			rangeKey: {
				type: String,
				default: 'label'
			},
			title: {
				type: String,
				default: ''
			},
			multiple: { // 是否可以多选
				type: Boolean,
				default: true
			},
			selectParent: { //是否可以选父级
				type: Boolean,
				default: false
			},
			foldAll: { //折叠时关闭所有已经打开的子集，再次打开时需要一级一级打开
				type: Boolean,
				default: false
			},
			confirmColor: { // 确定按钮颜色
				type: String,
				default: '' // #00a660
			},
			cancelColor: { // 取消按钮颜色
				type: String,
				default: '' // #757575
			},
			titleColor: { // 标题颜色
				type: String,
				default: '' // #757575
			},
			currentIcon: { // 展开时候的ic
				type: String,
				default: ''
			},
			defaultIcon: { // 折叠时候的ic
				type: String,
				default: ''
			},
			lastIcon: { // 没有子集的ic
				type: String,
				default: ''
			},
			border: { // 是否有分割线
				type: Boolean,
				default: false
			},
		},
		data() {
			return {
				loading: false,
				errorMessage: '',
				isOpened: false,
				showTree: false,
				treeList: [],
				selectIndex: -1,
				returnedItem: [] ,//定义一个空数组
				pids: [],
				ancestorsIds: [],
				childNums: [],
				inputSelected: [],
			}
		},
		watch: {
			defaultRange:{
				immediate:true,
				// 监听默认选择的数组
				handler(defaultRange) {
					if(defaultRange.length > 0 ){
						this._defaultSelect()
					}else{
						this.inputSelected = []
					}
				}
			},
			range: {
				deep: true,
				handler(list) {
					this._initTree(list);
				}
			},
			multiple() {
				if (this.range.length) {
					this._reTreeList();
				}
			},
			selectParent() {
				if (this.range.length) {
					this._reTreeList();
				}
			},
		},
		mounted() {
			this._initTree();
		},
		methods: {
			handleInput() {
				this.isOpened = true
				this._show()
			},
			/** 输入框点击图标删除 */
			clear(selected,index) {
				// this._treeItemSelect(selected,index)
				this.treeList.forEach((item1,index) => {
					if(selected.id == item1.id){
						this.treeList[index].checked = !this.treeList[index].checked
					}
				})
				this.syncChecked(this.treeList, selected.id, this.treeList[index].checked)
				this.inputSelected.splice(index,1)
				// 取消选父级, 子级自动取消全选
				this.treeList.forEach((item1,index) => {
					if(selected.id == item1.id && item1.parentId.length == 0){
						this.inputSelected = []
					}
				})
				this.$emit("clear", {selected,index});
		    },
		 	_show() {
				this.showTree = true
			},
			_hide() {
				this.showTree = false
			},
			_cancel() {
				this._hide()
				this.isOpened = false
				this.$emit("cancel", '');
			},
			_confirm() {
				// 处理所选数据 
				let rt = [],
					obj = {};
				this.treeList.forEach((v, i) => {
					if (this.treeList[i].checked) {
						rt.push({
							text:this.treeList[i].label,
							label:this.treeList[i].label,
							id:this.treeList[i].id,
							checked:this.treeList[i].checked,
							rank:this.treeList[i].rank,
						})
					}
				})
				this._hide()
				this.isOpened = false
				this.inputSelected = rt
				this.$emit("confirm", rt);
			},
			//扁平化树结构 
			_renderTreeList(list = [], rank = 0, parentId = [], parents = []) {
				// 如果这两个参数都没设置的话就全都收起来 
				let openRank = this.openRank ? (rank < this.openRank) : false; 
				// 如果设置了层级，那么需要让层级的上一级箭头是收起状态，否则需要通过点击触发的事件才能把数据展示出来
				let showRank = this.openRank ? (rank < this.openRank - 1) : false;
				if (this.showAllFlod) {
					openRank = showRank = true;
				}
				list.forEach(item => {
					this.treeList.push({
						id: item[this.idKey],
						label: item[this.rangeKey],
						staffPost:item.staffPost,
						source: item,
						parentId, // 父级id数组
						parents, // 父级id数组
						rank, // 层级
						showChild: Boolean(showRank), //箭头怎么展示
						open: Boolean(showRank), //是否打开
						show: Boolean(openRank || rank === 0), // 自身是否显示
						hideArr: [],
						orChecked: item.checked ? item.checked : false,
						checked: item.checked ? item.checked : false,
						childNum: 0,
					})
					
					if (Array.isArray(item.children) && item.children.length > 0) {
						let parentid = [...parentId],
							parentArr = [...parents];
						delete parentArr.children
						parentid.push(item[this.idKey]);
						parentArr.push({
							[this.idKey]: item[this.idKey],
							[this.rangeKey]: item[this.rangeKey]
						})
						// lazy
						if(!this.lazy) {
							this._renderTreeList(item.children, rank + 1, parentid, parentArr)
						}
					} else {
						this.treeList[this.treeList.length - 1].lastRank = true;
					}
				})
			},
			// 处理默认选择
			_defaultSelect() {
				this.treeList.forEach((v, i) => {
					this.defaultRange.forEach((v2, i2) => {
						if(v2.id == v.id ){
							v.open = true;
							v.checked = true;
							v2.text = v.label;
							v2.open = true;
							v2.showChild = true;
							this.inputSelected.push(v2)
						}	 
					})
				}) 
				// this.treeList.forEach((v, i) => {
				// 	if (v.checked) {
				// 		this.treeList.forEach((v2, i2) => {
				// 			if (v.parentId.toString().indexOf(v2.parentId.toString()) >= 0) {
				// 				v2.show = true
				// 				if (v.parentId.includes(v2.id)) {
				// 					v2.showChild = true;
				// 					v2.open = true;
				// 				}
				// 			}
				// 		})
				// 	}
				// })
				
			},
			getOwn(id, arr){
			  //利用foreach循环遍历
			  arr.forEach((item) => {
				//判断递归结束条件
				if(item[this.idKey] == id)
				{       
				  // 存储数据到空数组
				  this.returnedItem = item
				}
				  else if(item.children != null) //判断chlidren是否有数据
				{
				  //递归调用
				  this.getOwn(id, item.children);                 
				}                   
			  })
			  return this.returnedItem
			},
			setShow (id, arr, isShow) {
				arr.forEach((item, index) => {
					if(item.parentId.includes(id)) {
						this.treeList[index].showChild = isShow
						this.treeList[index].show = isShow
					} else if (item.children !== undefined) {
						this.setShow(id, item.children, isShow)
					}
				})
			},
			// 点击
			_treeItemTap(item, index) {
				if (item.lastRank === true) {
					//点击最后一级时触发事件
					this.treeList[index].checked = !this.treeList[index].checked
					this._fixMultiple(index)
					return;
				}
				let id = item.id;
				item.showChild = !item.showChild;
				// qingqian
				if(item.showChild) {
					const range = this.range
					const parentIdArr = item.parentId
					// 找到当前元素
					const own = this.getOwn(id, range)
					const checkedChildren = own.children
					// 子元素插入的索引位置
					const nextIndex = this.treeList.findIndex(itemT => itemT.id === item.id)
					if(checkedChildren === undefined || checkedChildren.length < 1) {
						return
					}
					// 子节点数量 
					this.treeList[index].childNum = checkedChildren.length
					const newRank = item.rank + 1
					checkedChildren.forEach(itemC => {
						const childObj = {
							id: itemC[this.idKey],
							// label: itemC[this.rangeKey],
							label: itemC.label,
							source: {},
							parentId: [item.id], // 父级id数组
							parents: [item], // 父级id数组
							rank: newRank, // 层级
							showChild: false, //子级是否显示
							open: false, //是否打开
							show: 1, // 自身是否显示
							hideArr: [],
							orChecked:  this.treeList[index].checked,
							checked:  this.treeList[index].checked,
						}
						if(!this.treeList.some(itemT => itemT.id === itemC[this.idKey])) {
							this.treeList.splice(nextIndex+1,0,childObj)
						}
					})
				}
				// 展开/隐藏子级/孙级
				let list = this.treeList
				item.open = item.showChild ? true : !item.open;
				list.forEach((childItem, i) => {
					if (item.showChild === false) {
						//隐藏所有子级
						if (!childItem.parentId.includes(id)) {
							return;
						}
						//TODO: 修改
						if (!this.foldAll) {
							if (childItem.lastRank !== true && !childItem.open) {
								childItem.showChild = false;
								this.setShow(childItem.id, this.treeList, false)
							}
							// 为隐藏的内容添加一个标记
							if (childItem.show) {
								childItem.hideArr[item.rank] = id
							}
						} else {
							if (childItem.lastRank !== true) {
								childItem.showChild = false;
								// 继续隐藏子级的的子级
								this.setShow(childItem.id, this.treeList, false)
							}
						}
						if(childItem.children !== undefined) {
							childItem.children.forEach((childItem1, i1) => {
								if(!childItem1.parentId.includes(childItem.id)) {
									return
								}
								childItem.children[i1].showChild = false
								childItem.children[i1].show = false
							})
						}
						childItem.show = false;
					} else {
						// 打开子集
						if (childItem.parentId[childItem.parentId.length - 1] === id) {
							childItem.show = true;
						}
						// 打开被隐藏的子集
						if (childItem.parentId.includes(id) && !this.foldAll) {
							if (childItem.hideArr[item.rank] === id) {
								childItem.show = true;
								if (childItem.open && childItem.showChild) {
									childItem.showChild = true
								} else {
									childItem.showChild = false
								}
								childItem.hideArr[item.rank] = null
							}
						}
					}
				})
			},
			// 通过父id处理子级
			syncChecked (trees, pid, checked) {
				trees.forEach((item,index) => {
					if(item.parentId.includes(pid)) {
						this.treeList[index].checked = checked
						this.syncChecked(trees, item.id, checked)
					} else if(item.children !== undefined) {
						this.syncChecked(item.children, pid, checked)
					}
				})
			},
			// 获取父级往上所有层级的id 并同步状态
			setAncestors (pids, checked) {
				this.treeList.forEach((item,index) => {
					if(pids.includes(item.id)) {
						if(checked && this.childNums[item.id] !== undefined && item.childNum === this.childNums[item.id]) {
						// 子级全部选中, 父级才选中
							this.treeList[index].checked = true
						} else {
							this.treeList[index].checked = false
						}
						this.setAncestors(item.parentId, checked)
					} 
				})
			},
			_treeItemSelect(item, index) {
				// this.treeList.forEach((item1,index) => {
				// 	if(item.id == item1.id){
				// 		this.treeList[index].checked = !this.treeList[index].checked
				// 	}
				// })
				this.treeList[index].checked = !this.treeList[index].checked
				// 选父级, 子级自动全选 
				this.syncChecked(this.treeList, item.id, this.treeList[index].checked)
				if( item.rank && item.rank > 0) {
					item.parentId.forEach((pid, indexP) => {
						const parent = this.treeList.filter(i => i.id === pid)
						const childNum = parent.length > 0 ? parent[0].childNum : 0
						if(this.childNums[pid] === undefined) {
							this.childNums[pid] = 1
						} else if(this.childNums[pid] < childNum) {
							this.childNums[pid]++
						}
					})
					//子级选择/选满/取消选择, 父级往上同步状态 
					this.setAncestors(item.parentId, this.treeList[index].checked)
				}
				this._fixMultiple(index)
			},
			// 处理单选多选
			_fixMultiple(index) {
				if (!this.multiple) {
					// 如果是单选
					this.treeList.forEach((v, i) => {
						if (i != index) {
							this.treeList[i].checked = false
						} else {
							this.treeList[i].checked = true
						}
					})
				}
			},
			// 重置数据
			_reTreeList() {
				this.treeList.forEach((v, i) => {
					this.treeList[i].checked = v.orChecked
				})
			},
			_initTree(range = this.range){
				this.treeList = [];
				this._renderTreeList(range);
				if(this.defaultRange.length > 0 ){
					this._defaultSelect()
				}
			}
		},
	}
</script>
<style scoped>
	@import "./style.css";
	.uni-data-tree {
		position: relative;
		font-size: 14px;
		/* min-width:275px; */ 
		/* max-width:275px; */
	}

	.error-text {
		color: #DD524D;
	}

	.input-value {
		border: 1px solid #e5e5e5;
		border-radius: 5px;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		align-items: center;
		flex-wrap: wrap;
		/* word-wrap:break-word; */
		/* white-space: normal; */
		font-size: 14px;
		padding: 0 5px 0 10px;
		line-height: 35px;
		font-size: 13px;
		/* overflow: hidden; */
		/* #ifdef APP-NVUE */
		/* height: 40px; */
		/* #endif */
		background: #fff;
	}

	.selected-area {
		flex: 1;
		overflow: hidden;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
	}

	.load-more {
		/* #ifndef APP-NVUE */
		margin-right: auto;
		/* #endif */
		/* #ifdef APP-NVUE */
		width: 40px;
		/* #endif */
	}

	.selected-list {
		/* #ifndef APP-NVUE */
		display: flex;
		padding: 2px 0px;
		/* #endif */
		flex-direction: row;
		flex-wrap: wrap;
		word-break: break-all;
		line-break: anywhere;
		align-items: center;
		
	}

	.selected-item {
		background: #e6f6ef;
		color: #00a660;
		borde:1px solid #99dbbf;
		padding:3px 5px;
		line-height: 20px;
		margin: 2px 8px 2px 0;
		border-radius: 3px;
		/* flex-direction: row; */
		/* #ifndef APP-NVUE */
		/* white-space: nowrap; */
		/* #endif */
	}
	.icon-clear {
		margin-left: 3px;
		background: #e6f6ef;
		color: #00a660;
		borde:1px solid #99dbbf;
		display: inline-block;
		/* padding:5px; */
		/* line-height: 20px; */
		/* margin: 2px 0 2px 3px; */
	}

	.placeholder {
		color: #666;
		font-size: 28rpx;
	}

	.input-split-line {
		opacity: .5;
	}

	.arrow-area {
		line-height: 35px;
		position: relative;
		width: 20px;
		/* #ifndef APP-NVUE */
		margin-left: auto;
		display: flex;
		/* #endif */
		justify-content: center;
		transform: rotate(-45deg);
		transform-origin: center;
	}

	.input-arrow {
		width: 7px;
		height: 7px;
		border-left: 1px solid #999;
		border-bottom: 1px solid #999;
	}

	.uni-data-tree-cover {
		position: fixed;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, .4);
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		z-index: 100;
	}

	.uni-data-tree-dialog {
		position: fixed;
		left: 0;
		top: 20%;
		right: 0;
		bottom: 0;
		background-color: #FFFFFF;
		border-top-left-radius: 10px;
		border-top-right-radius: 10px;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		z-index: 102;
		overflow: hidden;
		/* #ifdef APP-NVUE */
		width: 750rpx;
		/* #endif */
	}

	.dialog-caption {
		position: relative;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		/* border-bottom: 1px solid #f0f0f0; */
	}

	.title-area {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		align-items: center;
		/* #ifndef APP-NVUE */
		margin: auto;
		/* #endif */
		padding: 0 10px;
	}

	.dialog-title {
		/* font-weight: bold; */
		line-height: 44px;
	}

	.dialog-close {
		position: absolute;
		top: 0;
		right: 0;
		bottom: 0;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		align-items: center;
		padding: 0 15px;
	}

	.dialog-close-plus {
		width: 16px;
		height: 2px;
		background-color: #666;
		border-radius: 2px;
		transform: rotate(45deg);
	}

	.dialog-close-rotate {
		position: absolute;
		transform: rotate(-45deg);
	}

	.picker-view {
		flex: 1;
		overflow: hidden;
	}

	/* #ifdef H5 */
	@media all and (min-width: 768px) {
		.uni-data-tree-cover {
			background-color: transparent;
		}

		.uni-data-tree-dialog {
			position: absolute;
			top: 55px;
			height: auto;
			min-height: 400px;
			max-height: 50vh;
			background-color: #fff;
			border: 1px solid #EBEEF5;
			box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
			border-radius: 4px;
			overflow: unset;
		}

		.dialog-caption {
			display: none;
		}

		
	}

	/* #endif */

	/* picker 弹出层通用的指示小三角, todo：扩展至上下左右方向定位 */
	/* #ifndef APP-NVUE */
	.uni-popper__arrow,
	.uni-popper__arrow::after {
		position: absolute;
		display: block;
		width: 0;
		height: 0;
		border-color: transparent;
		border-style: solid;
		border-width: 6px;
	}

	.uni-popper__arrow {
		filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
		top: -6px;
		left: 10%;
		margin-right: 3px;
		border-top-width: 0;
		border-bottom-color: #EBEEF5;
	}

	.uni-popper__arrow::after {
		content: " ";
		top: 1px;
		margin-left: -6px;
		border-top-width: 0;
		border-bottom-color: #fff;
	}
	/* #endif */
	</style>
